package com.sxpi.zixun.controller.upload;

import com.sxpi.zixun.common.enums.AdminErrorResultEnum;
import com.sxpi.zixun.common.ex.PugValidatorException;
import com.sxpi.zixun.controller.BaseController;
import com.sxpi.zixun.pojo.Resources;
import com.sxpi.zixun.service.resources.IResourcesService;
import com.sxpi.zixun.service.upload.UploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Description
 * @Author sgl
 * @Date 2018-05-15 14:04
 */
@Controller
public class UploadController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private UploadService uploadService;

    @Autowired
    private IResourcesService resourcesService;

    /**
     * MultipartFile里面有个localhost中存放的是临时文件，上传的时候，先会把文件写入到临时目录当中，最后在copy的指定的磁盘中，最终在删除临时文件
     * 这样可以防止垃圾文件，保证磁盘中的文件都是完整有效的(这样可以保证上传文件的有效性)
     * @param file
     * @param request
     * @return
     * @throws IOException
     * @throws ServletException
     */
    // 上传地址：http://localhost:8877/admin/upload/file
    @PostMapping("/upload/file")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        if(file.getSize() > 1024 * 1024 * 2){
            throw new PugValidatorException(AdminErrorResultEnum.FILE_UPLOAD_LIMIT_ERROR);
        }
        if(!file.getContentType().equalsIgnoreCase("image/png") &&
                !file.getContentType().equalsIgnoreCase("image/jpg") &&
                !file.getContentType().equalsIgnoreCase("image/jpeg")){
            throw new PugValidatorException(AdminErrorResultEnum.FILE_UPLOAD_TYPE_ERROR);
        }
        // 文件上传如何传递参数
        String dir = request.getParameter("dir");
        if(StringUtils.isEmpty(dir)){
            dir = "course";
        }
        // handler调用文件上传的service 得到文件的虚拟路径
        String filepath = uploadService.uploadImg(file,dir);
        return filepath;
    }

    /**
     * 本地文件上传返回json
     * @param file
     * @param request
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @PostMapping("/upload/filemap")
    @ResponseBody
    public Map<String,Object> uploadJson(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
        if (file.isEmpty()) {
            return null;
        }
        // 2M
        if(file.getSize() > 1024 * 1024 * 2){
            throw new PugValidatorException(AdminErrorResultEnum.FILE_UPLOAD_LIMIT_ERROR);
        }
        if(!file.getContentType().equalsIgnoreCase("image/png") &&
                !file.getContentType().equalsIgnoreCase("image/jpg") &&
        !file.getContentType().equalsIgnoreCase("image/jpeg")){
            throw new PugValidatorException(AdminErrorResultEnum.FILE_UPLOAD_TYPE_ERROR);
        }
        String dir = request.getParameter("dir");
        if(StringUtils.isEmpty(dir)){
            dir = "course";
        }
        // handler调用文件上传的service 得到文件的虚拟路径
        Map<String,Object> map = uploadService.uploadImgMap(file,dir);
        // 资源入库 设计模式--- 观察设计模式
        String cid = request.getParameter("cid");
        Resources resources = new Resources();
        resources.setFilename(String.valueOf(map.get("filename")));
        resources.setNewname(String.valueOf(map.get("newname")));
        resources.setStatus(1);
        resources.setIsdelete(0);
        resources.setResourceId(new Long(cid));
        resources.setType(1);
        resources.setFilesize(String.valueOf(map.get("size")));
        resources.setExt(String.valueOf(map.get("ext")));
        resources.setPath(String.valueOf(map.get("url")));
        resources.setDownpath(String.valueOf(map.get("url")));
        resources.setIspublic(1);
        resourcesService.saveOrUpdate(resources);
        // 返回资源ID
        map.put("resources",resources);
        return map;
    }
}
